import { defaultShouldUpdate, nextTick } from '@/utils';
import { useState } from 'react';
import { useRaf } from '.';

/**
 * @param {Object} form                                     antd@4的form实例 FormInstance
 * @param {String|String[]} name                            antd@4的name
 * @param {Function} getter                                 取值格式化
 * @param {function(any, any): boolean} shouldUpdate        是否需要更新
 * @return {any}
 */
function useFormValue(form, name = null, getter = (v) => v, shouldUpdate = defaultShouldUpdate) {
  const get = () => {
    if (!form) return null;
    if (name) return form.getFieldValue(name);
    return form.getFieldsValue();
  };

  const [state, update] = useState(getter(get()) ?? null);
  // raf会阻塞浏览器渲染，所以在raf中用nextTick
  useRaf(() => {
    nextTick(() => {
      const value = getter(get()) ?? null;
      if (shouldUpdate(value, state)) {
        update(value);
      }
    });
  });
  return state;
}

export default useFormValue;
